/* eslint-disable */
import _ from 'lodash'
import http from './httpRequest'
import moment from 'dayjs'
import { ElMessage, ElLoading } from 'element-plus'

export const getToken = () => {
    return sessionStorage.getItem('all_token')
}

export const setToken = (token: string) => {
    sessionStorage.setItem('all_token', token)
}

export const getCode = () => {
    return sessionStorage.getItem('all_code')
}

export const setCode = (code: string) => {
    return sessionStorage.setItem('all_code', code)
}

export const getCodes = () => {
    return sessionStorage.getItem('all_codes')
}

export const setCodes = (code: string) => {
    return sessionStorage.setItem('all_codes', code)
}

export const getVersion = () => {
    return sessionStorage.getItem('tms_web_version')
}

export const setVersion = (version: string) => {
    sessionStorage.setItem('tms_web_version', version)
}

export const getTenantCode = () => {
    return sessionStorage.getItem('gksk-tenant-code')
}

export const setTenantCode = (code: string) => {
    sessionStorage.setItem('gksk-tenant-code', code)
}

export const getTenantId = () => {
    return sessionStorage.getItem('gksk-tenant-id')
}

export const setTenantId = (id: string) => {
    sessionStorage.setItem('gksk-tenant-id', id)
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key: string | string[]) {
    if (!key) {
        return true
    }
    const permissions = JSON.parse(sessionStorage.getItem('permissions') || '[]')
    if (Array.isArray(key)) {
        return key.some(k => permissions.indexOf(k) !== -1)
    }
    return permissions.indexOf(key) !== -1
}

export async function dict(val: string | number, type: string) {
    const { data } = await http({
        url: http.adornUrl(`/base/mgt/dictData/dictDataSelector/${type}`),
        params: http.adornParams({
        })
    })
    if (val === 'list_all') {//返回字典数据集合
        return data.data
    }
    const items = data.data
    const item = items.find(res => res.dictValue === val)
    // console.log('dict-item', item, 'val', val);

    if (item) {
        return item.dictLabel
    }
    return ''
}


/**
 * 树形结构
 * @param list 
 * @param id 
 * @param pId 
 * @returns 
 */
export function treeData(list: any[], id: string, pId: string) {
    let treeList: any[] = []
    if (id && pId) {
        list.forEach((res: any) => {
            const parent = list.find(next => next[id] === res[pId]);
            if (!parent) {
                treeList.push(res);
            } else {
                parent.children = parent.children || [];
                parent.children.push(res);
            }
        });
    }

    return treeList
}


/**
 * 附件下载
 * @param {*} payload 
 * @param {*} callback 
 * @param {*} method 
 */
export function download(payload: { url/*接口地址*/: string, filename/*文件名称*/: string, params/*接口参数*/: { [prop: string]: string | number | string[] | number[] }, _type/*文档类型*/: string }, callback/*回调函数，下载完毕执行*/: (blob) => void, method = 'get', config/*axios配置*/ = <{ [prop: string]: string | number | string[] | number[] }>{}) {
    http({
        url: http.adornUrl(payload.url),
        method: method,
        [method.toLocaleUpperCase() === 'GET' ? 'params' : 'data']: (http as any)["adorn" + (method.toLocaleUpperCase() === 'GET' ? 'Params' : 'Data')]({
            ...payload.params
        }, false),
        responseType: 'blob',
        ...config
    }).then((res) => {
        const { data } = res
        const contentType = res.headers['content-type'] || ''
        if (contentType.includes('application/json')) {
            return callback && callback(500)
        }

        const blob = new Blob([data], { type: payload._type || 'text/plain' })
        if (payload.params.stop) {
            callback && callback(blob)
        } else {
            let fileName = ''
            if (!payload.filename) {
                fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
            }
            const a = document.createElement('a')
            const now = moment().format("YYYY-MM-DD HH:mm:ss");
            const nvg = window.navigator as any
            if (nvg.msSaveOrOpenBlob) {
                nvg.msSaveOrOpenBlob(
                    blob,
                    `file${now}_${payload.filename || fileName}`
                );
            } else {
                a.download = payload.filename || fileName
                a.href = URL.createObjectURL(blob)
                a.click()
            }
            callback && callback(blob)
        }
    }).catch(() => callback && callback(null))
}

export function parseZhNum(index: number) {
    const zhNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']

    return zhNums[index]
}

export function getParams(qForm: any) {
    const form: any = {}
    Object.keys(qForm).forEach(key => {
        const type = typeof qForm[key]
        if (['string', 'number'].includes(type)) {
            form[key] = qForm[key]
        }
    })
    return form
}

export function toHump(name) {
    return name.replace(/\/(\w)/g, function (_all, letter) {
        return letter.toUpperCase();
    });
}

export function camelToSnake(str) {
    return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
}


export const permissions: string[] = []
export function setFullPath(data) {
    data.forEach(res => {
        if (res.permissions.length) {
            permissions.push(...res.permissions)
        }
        if (!res.fullPath) {
            res.fullPath = res?.path
            if (!res?.fullPath?.startsWith('/')) {
                res.fullPath = '/' + res.fullPath
            }
        }
        if (res.meta) {
            res.title = res.meta.title
            res.icon = res.meta.icon
            if (res.icon === '#') {
                res.icon = ''
            }
        } else {
            res.meta = {
            }
        }
        if (res.children) {
            res.type = 'folder'
            res.children.forEach(next => {
                if (!next.path?.startsWith('/')) {
                    next.path = '/' + next.path
                }
                next.fullPath = res.fullPath + next.path
                next.fullName = toHump(next.fullPath)
                next.parent = res
                if (next.children) {
                    next.type = 'folder'
                    setFullPath(res.children)
                } else {
                    next.type = 'file'
                    next.component = next.component || (res.fullPath + next.path)
                    if (next.permissions.length) {
                        permissions.push(...next.permissions)
                    }
                    if (next.meta) {
                        next.meta.keepAlive = true
                        next.title = next.meta.title
                        next.icon = next.meta.icon
                        if (next.icon === '#') {
                            next.icon = ''
                        }
                    } else {
                        next.meta = {
                            keepAlive: true
                        }
                    }
                }
            })
        } else {
            res.type = 'file'
            res.component = res.component || (res.fullPath)
            res.fullName = toHump(res.fullPath)
        }
    })
    return data
}
export function treeNode(data) {

    return data.map(item => {
        if (item.children.length > 0) {
            return {
                path: item.path,
                name: item.name,
                component: item.component,
                fullPath: item.path,
                permissions: item.buttons?.map(res => res.bizCode) || [],
                meta: {
                    title: item.name
                },
                children: treeNode(item.children),

            }
        } else {
            return {
                path: item.path,
                name: item.name,
                component: item.component,
                fullPath: item.path,
                permissions: item.buttons?.map(res => res.bizCode) || [],
                meta: {
                    title: item.name
                },

            }
        }
    })

}
/**
 * 字段驼峰 替换成下划线_ label
 */
export function toUnderScore(label: string) {
    return label.replace(/([A-Z])/g, function (letter) {
        return '_' + letter.toLowerCase();
    });
}


export function joinNumber(n: number, p: string) {
    const str = n?.toString() || ''
    return str.replace(/\B(?=(\d{3})+(?!\d))/g, p)
}

export function setSize() {
    if (document.body.clientWidth > 1910) {
        if (document.body.clientHeight < 1070) {
            document.documentElement.style.fontSize = '86px'
        } else {
            document.documentElement.style.fontSize = '100px'
        }
    }
}

export function randomColor() {
    let str = "#";
    let arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
    for (let i = 0; i < 6; i++) {
        let num = parseInt((Math.random() * 16).toString());
        str += arr[num];
    }
    return str;
}
export function handleCommonTimeRender(text: string, format = 'YYYY-MM-DD HH:mm:ss') {
    return text && moment(text).format(format);
}
export function handleCommonTimeRenderYmd(text: string, format = 'YYYY-MM-DD') {
    return text && moment(text).format(format);
}


export function setUrl(url) {
    // if (url.startsWith('/base')) {
    //     return 'http://10.117.3.6:30707/spl/tms' + url
    // }
    // if (url.startsWith('/disp')) {
    //     return 'http://10.117.3.6:30707/spl/tms' + url
    // }
    // if (url.startsWith('/order')) {
    //     return 'http://10.117.3.6:30707/spl/tms' + url
    // }
    // if (url.startsWith('/rule')) {
    //     return 'http://10.117.3.6:30707/spl/tms' + url
    // }
    // if (url.startsWith('/track')) {
    //     return 'http://10.117.3.6:30707/spl/tms' + url
    // }
    return window.SITE_CONFIG['baseUrl'] + url
}

export function pdfPrint(url: string, params) {
    const loadingInstance = ElLoading.service({
        text: '打印资源准备中...'
    })
    download({
        url: url,//请求地址
        filename: '',//filename 为 ''时，会取接口返回的文件名称，也可自定义
        params: {
            stop: true,
            ...params
        },
        _type: 'application/pdf'
    }, (blob) => {
        if (blob == 500) {
            ElMessage.warning('暂无可打印的单据')
            loadingInstance.close()
            return
        }
        let date = (new Date()).getTime()
        let ifr = document.createElement('iframe')
        ifr.style.border = 'none'
        ifr.style.display = 'none'
        ifr.style.pageBreakBefore = 'always'
        ifr.setAttribute('id', 'printPdf' + date)
        ifr.setAttribute('name', 'printPdf' + date)
        ifr.src = window.URL.createObjectURL(blob)
        document.body.appendChild(ifr)
        let ordonnance = (document.getElementById('printPdf' + date) as any)?.contentWindow
        if (blob.size > 0) {
            ordonnance.onload = () => {
                setTimeout(() => {
                    loadingInstance.close()
                    ordonnance.print()
                }, 100)
            }
        } else {
            loadingInstance.close()
            ElMessage.warning('暂无可打印的单据')
        }
        window.URL.revokeObjectURL(ifr.src)

    }, 'post', {})

}

export function blobToUrl(url: string, params) {
    download({
        url: url,//请求地址
        filename: '',//filename 为 ''时，会取接口返回的文件名称，也可自定义
        params: {
            stop: true,
            ...params
        },
        _type: 'application/pdf'
    }, (blob) => {
        if (blob == 500) {
            ElMessage.warning('数据获取失败')
            return
        }
        return window.URL.createObjectURL(blob)
    }, 'post', {})
}


export function upperLeadCase(str: string) {
    if (typeof str !== 'string') {
        return ''
    }
    return str.slice(0, 1).toUpperCase() + str.slice(1)
}